//
//  HTTravelViewController.m
//  HeartTravel
//
//  Created by lanou on 15/10/31.
//  Copyright © 2015年 陈文杰. All rights reserved.
//

#import "HTTravelViewController.h"
#import "HTTravelCell.h"
#import "HTTravelModel.h"
#import "PKRequestManager.h"
#import "HTTravelDetailViewController.h"
#import "SDCycleScrollView.h"

#import "MJRefresh.h"
#import "FMDatabase.h"

#define kURL @"http://api.breadtrip.com/trips/hot/?start=0&count=20&is_ipad=true"

@interface HTTravelViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) UITableView *mainTableView;
@property (nonatomic, strong) NSMutableArray *dataSourceArray;
@property (nonatomic, strong) SDCycleScrollView *cycleScrollView;

@property (nonatomic, strong) FMDatabase *dataBase;

@end

@implementation HTTravelViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationController.navigationBar.hidden = YES;
    self.titleLabel.text = @"游记";
    self.view.backgroundColor = [UIColor whiteColor];
    
    _mainTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 70, SCREEN_WIDTH, SCREEN_HEIGHT - 120)];
    _mainTableView.delegate = self;
    _mainTableView.dataSource = self;
    [_mainTableView registerClass:[HTTravelCell class] forCellReuseIdentifier:@"cell"];
    _mainTableView.rowHeight = 230;
    _mainTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    NSMutableArray *arr = [NSMutableArray array];
    for (int i = 0; i<4; i++) {
        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"%d.jpg", i]];
        [arr addObject:image];
    }
    _cycleScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 200) imagesGroup:arr];
    _cycleScrollView.pageControlAliment = SDCycleScrollViewPageContolAlimentRight;
    _mainTableView.tableHeaderView = _cycleScrollView;
    
    [self.view addSubview:_mainTableView];
    [self requestData];
    
    __weak HTTravelViewController *travelVC = self;
    _mainTableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [travelVC requestData];
        [_mainTableView.header endRefreshing];
    }];
    
    _mainTableView.footer = [MJRefreshAutoFooter footerWithRefreshingBlock:^{
        [travelVC requestMoreData];
        [_mainTableView.footer endRefreshing];
    }];
    
    NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:@"HeartTravel.db"];
    _dataBase = [FMDatabase databaseWithPath:filePath];
    if ([_dataBase open]) {
        NSLog(@"数据库打开成功");
        [_dataBase executeUpdate:@"CREATE TABLE TRAVEL (id_name integer, cover_image text, name text, popular_place_str text, avatar_l text, user_name text)"];
    } else {
        NSLog(@"数据库打开失败");
    }
    
    FMResultSet *resultSet = [_dataBase executeQueryWithFormat:@"SELECT *FROM TRAVEL "];
    while ([resultSet next]) {
        NSNumber *id_name = [NSNumber numberWithInteger:[resultSet intForColumn:@"id_name"]];
        NSString *cover_image = [resultSet stringForColumn:@"cover_image"];
        NSString *name = [resultSet stringForColumn:@"name"];
        NSString *popular_place_str = [resultSet stringForColumn:@"popular_place_str"];
        NSString *avatar_l = [resultSet stringForColumn:@"avatar_l"];
        NSString *user_name = [resultSet stringForColumn:@"user_name"];
        
        HTTravelModel *model = [[HTTravelModel alloc] init];
        model.id_name = id_name;
        model.cover_image = cover_image;
        model.name = name;
        model.popular_place_str = popular_place_str;
        model.avatar_l = avatar_l;
        model.user_name = user_name;
        [self.dataSourceArray addObject:model];
    }
    [resultSet close];
}

- (NSMutableArray *)dataSourceArray {
    
    if (_dataSourceArray == nil) {
        _dataSourceArray = [NSMutableArray arrayWithCapacity:0];
    }
    return _dataSourceArray;
}

- (void)requestData {
    
    [PKRequestManager requestWithType:GET urlString:kURL parDic:nil finish:^(NSData *data) {
        [_dataBase executeUpdate:@"DELETE FROM TRAVEL"];
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves error:nil];
        [self.dataSourceArray removeAllObjects];
        for (NSDictionary *modelDic in dict[@"trips"]) {
            HTTravelModel *model = [[HTTravelModel alloc] init];
            [model setValuesForKeysWithDictionary:modelDic];
            [self.dataSourceArray addObject:model];
            
            [_dataBase executeUpdate:@"INSERT INTO TRAVEL (id_name, cover_image, name, popular_place_str, avatar_l, user_name) VALUES (?,?,?,?,?,?)", model.id_name, model.cover_image, model.name, model.popular_place_str, model.avatar_l, model.user_name];
        }
        [self.mainTableView reloadData];
        
    } error:^(NSError *error) {
        NSLog(@"请求失败");
    }];
}

- (void)requestMoreData {
    
    NSString *urlStr = [@"http://api.breadtrip.com/trips/hot/?start=" stringByAppendingFormat:@"%ld%@", self.dataSourceArray.count, @"&count=20&is_ipad=true"];
    [PKRequestManager requestWithType:GET urlString:urlStr parDic:nil finish:^(NSData *data) {
        
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves error:nil];
        
        for (NSDictionary *modelDic in dict[@"trips"]) {
            HTTravelModel *model = [[HTTravelModel alloc] init];
            [model setValuesForKeysWithDictionary:modelDic];
            [self.dataSourceArray addObject:model];
        }
        [self.mainTableView reloadData];
        
    } error:^(NSError *error) {
        NSLog(@"上提请求失败");
    }];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.dataSourceArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    HTTravelCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    HTTravelModel *model = _dataSourceArray[indexPath.row];
    [cell setConfigureModel:model];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    HTTravelDetailViewController *detailVC = [[HTTravelDetailViewController alloc] init];
    HTTravelModel *model = _dataSourceArray[indexPath.row];
    detailVC.id_name = model.id_name;
    detailVC.name = model.name;
    CATransition *animation = [CATransition animation];
    animation.duration = 1.0;
    animation.timingFunction = UIViewAnimationCurveEaseInOut;
    animation.type = @"rippleEffect";
    //animation.type = kCATransitionPush;
    animation.subtype = kCATransitionFromLeft;
    [self.view.window.layer addAnimation:animation forKey:nil];
    [self presentViewController:detailVC animated:YES completion:^{
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
